<!-- 活动详情-选择报名人员 -->
<template>
  <div class="not-registered-user">
    <a-drawer width="90%" :visible="visible" @close="handleCancel">
      <template slot="title">
        <div class="disFlxAC">
          <div class="_mr-20">选择报名人员</div>
          <a-alert
            v-if="activityInfo.activityType === 'other_join' && activityInfo.enrollVerify === 1"
            message="当前活动已开启报名审核，本次新增报名需要活动发布方审核通过后才报名成功。"
            banner
          />
        </div>
      </template>
      <div class="disFlx" style="padding-bottom: 40px;">
        <div style="min-width:400px;width:400px" class=" _mr-10">
          <a-list
            item-layout="horizontal"
            :data-source="selectedRecords"
            bordered
            :pagination="{
              simple: true
            }"
          >
            <div slot="header" class="disFlxJS">
              <span>已选人员</span>
              <a-button type="danger" ghost @click="handleDelAll">
                全部删除
              </a-button>
            </div>

            <a-list-item slot="renderItem" slot-scope="item">
              <div @click="handleDel(item.id)" slot="actions">
                <a-icon type="close" />
              </div>
              <a-list-item-meta>
                <div slot="title" style="font-size:12px;white-space: nowrap;margin-right: 20px;">
                  {{ item.leadingName }}
                </div>
              </a-list-item-meta>
              <div style="font-size:12px">{{ item.companyName }}</div>
            </a-list-item>
          </a-list>
        </div>
        <div style="flex:1">
          <a-form-model layout="inline" ref="form">
            <a-row :gutter="12">
              <a-col :md="6">
                <a-form-model-item label="关键词">
                  <a-input
                    v-model="queryParam.keyword"
                    placeholder="姓名/单位/手机号/职务"
                    allowClear
                    style="width: 100%"
                  />
                </a-form-model-item>
              </a-col>
              <a-col :md="6">
                <a-form-model-item label="单位身份">
                  <a-select
                    v-model="queryParam.memberRoleType"
                    mode="multiple"
                    placeholder="请选择单位身份"
                    allowClear
                    :showArrow="true"
                    class="min-width-15"
                  >
                    <a-select-option
                      v-for="dict in Dict.getLocal('companyIdentityDict')"
                      :key="dict.dictValue"
                      :value="dict.dictValue"
                      >{{ dict.dictLabel }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6">
                <a-form-model-item label="用户类型">
                  <a-select
                    v-model="queryParam.applyType"
                    placeholder="请选择"
                    :showArrow="true"
                    allowClear
                    mode="multiple"
                    class="min-width-15"
                  >
                    <a-select-option
                      v-for="dict in Dict.getLocal('applyTypeDict')"
                      :key="dict.dictValue"
                      :value="dict.dictValue"
                    >
                      {{ dict.dictLabel }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6">
                <a-form-model-item label="会员职务">
                  <a-select
                    v-model="queryParam.levelIds"
                    placeholder="请选择会员职务"
                    mode="multiple"
                    allowClear
                    :showArrow="true"
                    style="width: 150px"
                  >
                    <a-select-option v-for="item in memberLevels" :value="item.id" :key="item.id"
                      >{{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="6">
                <a-form-model-item label="小程序">
                  <a-select
                    v-model="queryParam.isLogin"
                    placeholder="请选择"
                    mode="multiple"
                    allowClear
                    :showArrow="true"
                    style="width: 150px"
                  >
                    <a-select-option
                      v-for="dict in Dict.getLocal('isLoginDict')"
                      :key="dict.dictValue"
                      :value="dict.dictValue"
                    >
                      {{ dict.dictLabel }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6">
                <a-form-model-item label="公众号">
                  <a-select
                    v-model="queryParam.isOfficialAccount"
                    placeholder="请选择"
                    mode="multiple"
                    allowClear
                    :showArrow="true"
                    style="width: 150px"
                  >
                    <a-select-option
                      v-for="dict in Dict.getLocal('isOfficialAccountDict')"
                      :key="dict.dictValue"
                      :value="dict.dictValue"
                    >
                      {{ dict.dictLabel }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6">
                <a-form-item label="用户标签">
                  <a-select
                    placeholder="请选择标签"
                    v-model="queryParam.tagId"
                    allowClear
                    :showArrow="true"
                    mode="multiple"
                    style="width: 180px"
                  >
                    <a-select-option v-for="(item, idx) in labelLists" :key="idx" :value="item.id" :label="item.name">
                      <span role="img" :aria-label="item.name"></span>
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="6">
                <a-button class="_mt-4" type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button class="_mt-4" style="margin-left: 8px" @click="handleReset">重置</a-button>
              </a-col>
            </a-row>
          </a-form-model>

          <div class="_pb-10 _pt-10 disFlxJS">
            <div>
              <span class="_mr-10 color9"
                >已勾选<span class="colorZS _pl-2 _pr-2 fw-7">{{ selectCount }}</span
                >位报名人员</span
              >
              <a-button v-if="total" type="primary" ghost @click="checkedAllMemberList"
                >{{ isAllChecked ? '取消勾选' : '勾选' }}"筛选条件"下全部<span class="fw-7 _pl-2 _pr-2">{{
                  total
                }}</span
                >位报名人员</a-button
              >
            </div>
          </div>

          <s-table
            ref="table"
            rowKey="id"
            :columns="columns"
            :data="loadData"
            :rowSelection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
              onSelect: onSelect,
              onSelectAll: onSelectAll,
              getCheckboxProps: getCheckboxProps
            }"
            :scroll="{ y: 500 }"
          >
            <!-- 用户信息 -->
            <template slot="userInfo" slot-scope="text, record">
              <div class="disFlxAC">
                <a-avatar v-if="record.avatar" size="default" :src="record.avatar" />
                <a-avatar v-else size="default" icon="user" />
                <div class="_pl-10">
                  <div>
                    <span>{{ record.leadingName }}</span>
                  </div>
                  <div>{{ record.phonenumber }}</div>
                </div>
              </div>
            </template>

            <!-- 单位身份 -->
            <span slot="memberRoleType" slot-scope="text">
              <DictTag :options="Dict.getLocal('companyIdentityDict')" :value="text" isText showBorder />
            </span>

            <!-- 用户类型 -->
            <span slot="applyType" slot-scope="text">
              <DictTag :options="Dict.getLocal('applyTypeDict')" :value="text" isText showBorder />
            </span>

            <!-- 小程序登录状态 -->
            <span slot="isLogin" slot-scope="text">
              <DictTag :options="Dict.getLocal('isLoginDict')" :value="text" isText />
            </span>

            <!-- 公众号关注状态 -->
            <span slot="isOfficialAccount" slot-scope="text">
              <DictTag :options="Dict.getLocal('isOfficialAccountDict')" :value="text" isText />
            </span>
          </s-table>
        </div>
      </div>

      <div
        v-if="visible"
        :style="{
          position: 'absolute',
          bottom: 0,
          padding: '10px 16px',
          textAlign: 'right',
          right: 0
        }"
      >
        <a-button style="margin-right: 8px" @click="handleCancel">
          取消
        </a-button>
        <a-button type="primary" @click="handleSubmit" :confirmLoading="confirmLoading">
          {{ okText }}
        </a-button>
      </div>
    </a-drawer>
  </div>
</template>

<script>
import { STable } from '@/components'
import { getTagUserList } from '@/api/member/grouping'
import { debounce } from '@/utils/common'
import DictTag from '@/components/DictTag'
import { memberLevelGetDownList,  } from '@/api/system/system'

export default {
  components: {
    STable,
    DictTag
  },
  data() {
    return {
      visible: false,
      // 查询参数
      activityInfo: {},
      activityId: '',
      activityTicketId: undefined,
      api: {
        apiList: null,
        apiIdList: null,
        submit: null
      },
      disabledFn: null,
      okText: '',

      // 审核表单
      columns: [
        { title: '用户', scopedSlots: { customRender: 'userInfo' }, width: 180 },
        { title: '单位', dataIndex: 'companyName', width: 180 },
        { title: '单位职务', dataIndex: 'companyPosition', width: 100 },
        { title: '单位身份', dataIndex: 'memberRoleType', width: 120, scopedSlots: { customRender: 'memberRoleType' } },
        { title: '用户类型', dataIndex: 'applyType', width: 120, scopedSlots: { customRender: 'applyType' } },
        { title: '会员职务', dataIndex: 'levelName', width: 120 },
        { title: '小程序', dataIndex: 'isLogin', width: 100, scopedSlots: { customRender: 'isLogin' } },
        {
          title: '公众号',
          dataIndex: 'isOfficialAccount',
          width: 120,
          scopedSlots: { customRender: 'isOfficialAccount' }
        }
      ],
      pagination: {
        current: 1,
        pageSize: 10
      },
      total: 0,
      loadData: parameter => {
        this.pagination.current = parameter.current
        let res = {}
        res = this.api.apiList(
          Object.assign(parameter, this.queryParam, {
            activityId: this.activityId,
            appUserInfoIds: this.activityInfo.appUserInfoIds
          })
        )
        res.then(r => {
          this.total = r.data.total
          r.data.records.forEach(v => {
            this.disabledFn(v)
          })
          return r
        })
        return res
      },
      queryParam: {
        keyword: undefined,
        applyType: [],
        levelIds: [],
        memberRoleType: [],
        tagId: [],
        isLogin: [],
        isOfficialAccount: []
      },
      selectedRowKeys: [],
      selectedRecords: [],
      memberLevels:[],
      labelLists: [],
      isAllChecked: false,
      confirmLoading: false
    }
  },
  inject: ['drd'],
  watch: {},
  computed: {
    signTime: {
      get() {
        return [this.queryParam.signStartTime, this.queryParam.signEndTime]
      },
      set(val) {
        this.queryParam.signStartTime = val[0]
        this.queryParam.signEndTime = val[1]
      }
    },
    downList() {
      return this.drd()
    },
    selectCount() {
      return this.selectedRecords.filter(f => !this.disabledFn(f)).length
    }
  },
  methods: {
    debounce,
    getCheckboxProps(record) {
      return {
        props: {
          disabled: record.disabled,
          defaultChecked: record.isRegister == 1,
          name: record.name
        }
      }
    },
    async memberLevel() {
      let res = await memberLevelGetDownList()
      this.memberLevels = res.data || []
    },
    moduleShow({ row, activityTicketId, apiList, apiIdList, submit, disabledFn, okText }) {
      
      this.isAllChecked = false
      this.activityTicketId = activityTicketId
      this.activityInfo = row
      this.activityId = row.id
      this.selectedRowKeys = []
      this.selectedRecords = []
      this.visible = true
      this.api.apiList = apiList
      this.api.apiIdList = apiIdList
      this.api.submit = submit
      this.disabledFn = disabledFn
      this.okText = okText
      this.getLabelList()
      this.memberLevel()
      this.$nextTick(() => {
        this.handleReload()
      })
    },

    getLabelList() {
      getTagUserList({ type: 0 }).then(res => {
        this.labelLists = res.data
      })
    },
    handleReload() {
      this.$refs.table.refresh()
    },
    //表格数据选中
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    onSelect(record, selected) {
      if (selected) this.selectedRecords.push(record)
      else this.selectedRecords = this.selectedRecords.filter(f => f.id != record.id)
    },
    onSelectAll(selected, _, changeRows) {
      if (selected) this.selectedRecords.push(...changeRows)
      else {
        const ids = changeRows.map(item => item.id)
        this.selectedRecords = this.selectedRecords.filter(f => !ids.includes(f.id))
        console.log('onSelectAll', this.selectedRecords)
      }
    },
    handleDel(id) {
      this.selectedRecords = this.selectedRecords.filter(f => id !== f.id)
      this.selectedRowKeys = this.selectedRowKeys.filter(item => id !== item)
    },
    handleDelAll() {
      this.selectedRecords = []
      this.selectedRowKeys = []
      this.isAllChecked = false
    },

    async checkedAllMemberList() {
      this.handleReload() // 刷新表格禁用条件

      if (this.isAllChecked) {
        this.handleDelAll()
        return
      }

      const res = await this.api.apiIdList({
        ...this.queryParam,
        activityId: this.activityId,
        appUserInfoIds: this.activityInfo.appUserInfoIds
      })

      if (res.code) throw new Error('查询当前搜索条件得人员id失败')
      if (!res.data || !res.data.appUserInfoIds || !res.data.appUserInfoIds.length) {
        throw new Error('当前搜索条件没有查到id')
      }
      this.selectedRowKeys = res.data.appUserInfoIds

      const rowsRes = await this.api.apiList({
        current: 1,
        pageSize: res.data.appUserInfoIds.length,
        ...this.queryParam,
        activityId: this.activityId,
        appUserInfoIds: res.data.appUserInfoIds
      })

      if (rowsRes.code) throw new Error('查询当前搜索条件得人员信息失败')

      this.selectedRecords = rowsRes.data.records
      this.isAllChecked = true
    },
    async handleSubmit() {
      try {
        this.confirmLoading = true
        await this.api.submit(this.selectedRecords)
        this.visible = false
      } catch (error) {
      } finally {
        this.confirmLoading = false
      }
    },
    handleCancel() {
      this.visible = false
      this.afterClose()
    },
    afterClose() {
      this.restFields()
    },
    restFields() {
      Object.keys(this.queryParam).forEach(k => {
        this.queryParam[k] = undefined
      })
    },
    handleReset() {
      this.restFields()
      this.$refs.table.refresh(true)
    }
  }
}
</script>

<style>
.ant-list-item-action {
  margin-left: 10px;
}
</style>
